package eleanor.ltd.isRealEstate.services;

import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.Session;

import eleanor.ltd.isRealEstate.dao.user.UserDAO;
import eleanor.ltd.isRealEstate.dao.user.group.UserGroupDAO;
import eleanor.ltd.isRealEstate.entities.user.User;
import eleanor.ltd.isRealEstate.model.MD5;
import eleanor.ltd.isRealEstate.security.AuthenticationException;

public class BasicAuthenticator implements Authenticator{

	public static final String AUTH_TOKEN = "authToken";

    @Inject
    private UserDAO userDAO;

    @Inject
    private Request request;
    
    @Inject
    private UserGroupDAO userGDAO;
    
    

    public void login(String username, String password)
                    throws AuthenticationException {
    		System.out.println("Password prije MD5: " + password + " " + username);
            password = MD5.md5(password);
            System.out.println("Password posle MD5: " + password);
            User user = userDAO.findByUserNameAndPassword(username, password);

            if (user == null) {
//            		errorPage.setMessage("The user doesn't exist");
            		
                    throw new AuthenticationException("The user doesn't exist");
                    
                    
            }

            request.getSession(true).setAttribute(AUTH_TOKEN, user);
            
            
    }

    public boolean isLoggedIn() {
            Session session = request.getSession(false);
            if (session != null) {
                    return session.getAttribute(AUTH_TOKEN) != null;
            }
            return false;
    }

    public void logout() {
            Session session = request.getSession(false);
            if (session != null) {
                    session.setAttribute(AUTH_TOKEN, null);
                    session.invalidate();
            }
    }

    public User getLoggedUser() {
            User user = null;

            if (isLoggedIn()) {
                    user = (User) request.getSession(true).getAttribute(AUTH_TOKEN);
            } else {
                    throw new IllegalStateException("The user is not logged !");
            }
            return user;
    }

	public boolean isAdmin() {
		String temp = "";
		temp = userGDAO.findAdministrator(getLoggedUser().getId());
		System.out.println("FROM FROM FROM FROM FROM FROM isAdmin: " + temp);
		if(temp.equalsIgnoreCase("Administrator")) {
			return true;
		} else {
			return false;
		}
	}


	
}
